//
//  AsrPlugin.m
//  Runner
//
//  Created by 陈云林 on 2019/7/3.
//  Copyright © 2019 The Chromium Authors. All rights reserved.
//

#import "AsrPlugin.h"
#import "AsrManager.h"

@interface AsrPlugin ()
@property (strong,nonatomic) AsrManager *asrManger;
@property (strong,nonatomic) FlutterResult result;
@end

@implementation AsrPlugin
+(void) registerWithRegistrar:(NSObject<FlutterPluginRegistrar>
                               *)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel
                                     methodChannelWithName:@"asr_plugin"
                                     binaryMessenger:[registrar messenger]];
    AsrPlugin *instance = [AsrPlugin new ];
    [registrar addMethodCallDelegate:instance channel:channel];
}

-(void)handleMethodCall:(FlutterMethodCall *)call result:
(FlutterResult)result{
    if ([@"start" isEqualToString:call.method]) {
        self.result = result;
        [[self _asrManger] start];
    }else if([@"stop" isEqualToString:call.method]){
        [[self _asrManger] stop];
    }else if([@"cancel" isEqualToString:call.method]){
        [[self _asrManger] cancel];
    }else{
        result(FlutterMethodNotImplemented);
    }
}

-(AsrManager *)_asrManger{
    if (!self.asrManger) {
        self.asrManger = [AsrManager initWith:^(NSString *message) {
            if(self.result){
                self.result(message);
                self.result = nil;
            }
        } failure:^(NSString *message) {
            if(self.result){
                self.result([FlutterError errorWithCode:@"ASR failure"
                                                message:message details:nil] );
                self.result = nil;
            }
        }];
    }
    return self.asrManger;
}
@end
